import 'dart:math';

import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../../tools/DL_drawNumbersView.dart';
import '../../tools/DL_generator.dart';
import '../../tools/KaL_drawNumbersView.dart';

class DL_generator_home extends StatefulWidget {
  DL_generator_home({
    super.key,
    this.pageController,
    this.generateSuccess,
    this.typeIndex,
  });
  PageController? pageController;
  int? typeIndex;
  Function(int)? generateSuccess;
  @override
  State<DL_generator_home> createState() => _DL_generator_homeState();
}

class _DL_generator_homeState extends State<DL_generator_home> {
  ///0:1pm,1:6pm,2:8pm,3:other
  int _typeIndex = 0;

  ///
  List<Widget> balls = [];
  List<Map> saveNumbers = [];

  var _numbersMap = {};

  late int scoredForNumbers = 0; //号码分析打分结果

  ///
  _goToGeneratorPage() {
    // HL_JKLocalStorage.setStringList(NL_config.NL_GeneratorNumbers, saveNumbers);
    // HL_JKLocalStorage.setBool(NL_config.NL_haveGeneratorNumbers, true);
    if (widget.pageController != null) {
      var Page = widget.pageController!;
      Page.jumpToPage(3);
    }
  }

  _generate() async {
    await _generateRandomNumbers(_typeIndex);
    if (widget.generateSuccess != null) {
      widget.generateSuccess!(scoredForNumbers);
    }
  }

  ///
  _generateRandomNumbers(int typeIndex) async {
    // 自定义范围
    int min = 30; // 最小值
    switch (typeIndex) {
      case 0:
        min = 42;
      case 1:
        min = 74;
        break;
      case 2:
        min = 30;
        break;
      case 3:
        min = 0;
        break;
    }
    int max = 99; // 最大值
    // 生成随机整数--前缀数字
    Random random = Random();
    int randomNumber = min + random.nextInt(max - min + 1);
    if (typeIndex == 3) {
      randomNumber = 0;
    }

    ///
    // _nextDrawnModel = KL_keralaLottoDataModel().nextDrawnModel;
    var firstNumString = randomNumber > 0 ? randomNumber.toString() : '';
    String randomNumbers =
        await DL_Generator.instance.generateNumbers(firstNumString);

    List balls = [];
    List<String> charArray = randomNumbers.split('');
    // numbersMap = charArray;
    for (var i = 0; i < charArray.length; i++) {
      var ball = {
        'number': charArray[i],
        'isRight': false,
        'isNormal': true
      }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
      balls.add(ball);
    }
    _numbersMap = {'title': '', 'balls': balls};

    scoredForNumbers = await DL_Generator.instance.scoredForNumbers;

    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _typeIndex = widget.typeIndex ?? 0;
    _generateRandomNumbers(_typeIndex);

    //延迟1秒
    Future.delayed(const Duration(milliseconds: 100), () {
      // setState(() {});
      if (widget.generateSuccess != null) {
        widget.generateSuccess!(scoredForNumbers);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    _typeIndex = widget.typeIndex ?? 0;
    //进度条比例
    double progress = scoredForNumbers / 100;
    return GestureDetector(
      onTap: () {
        debugPrint('go to generator');
        _goToGeneratorPage();
      },
      child: Container(
        height: 160,
        margin: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2), // 阴影颜色
              spreadRadius: 1, // 扩散半径
              blurRadius: 10, // 模糊半径
              offset: const Offset(0, 1), // 阴影偏移
            ),
          ],
          borderRadius: const BorderRadius.all(Radius.circular(10)),
          color: Colors.white,
        ),
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 110),
              child: Container(
                height: 50,
                // width: 300,
                decoration: const BoxDecoration(
                  // color: HexColor('#f6f6f6'),
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(10),
                      bottomRight: Radius.circular(10)),
                ),
                child: Stack(
                  children: [
                    SizedBox(
                      // color: Colors.white,
                      height: 50,
                      child: LinearProgressIndicator(
                        borderRadius: const BorderRadius.only(
                            bottomLeft: Radius.circular(10),
                            bottomRight: Radius.circular(10)),
                        backgroundColor: HexColor('##F6F6F6'), // 设置进度条背景颜色
                        valueColor: AlwaysStoppedAnimation<Color>(
                            HexColor('##C9FFCF')), // 设置进度条颜色
                        value: progress, // 设置进度值（0.0 - 1.0）
                      ),
                    ),
                    SizedBox(
                      height: 50,
                      child: Padding(
                        padding: const EdgeInsets.only(top: 10),
                        child: Row(
                          children: [
                            const SizedBox(width: 15),
                            const Text('AI scored your numbers:',
                                style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w300,
                                )),
                            const Spacer(),
                            Text(
                              scoredForNumbers.toString(),
                              style: TextStyle(
                                  fontWeight: FontWeight.w500,
                                  fontSize: 13,
                                  color: HexColor('#2BA471')),
                            ),
                            const SizedBox(width: 20),
                            Image.asset('assets/sys_imgs/EJ_union.png',
                                width: 8.0, height: 13.0),
                            const SizedBox(width: 15),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              height: 120,
              width: double.infinity,
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(
                    Radius.circular(10),
                  )),
              child: Column(
                children: [
                  Container(
                    color: Colors.white,
                    margin: const EdgeInsets.only(left: 10, right: 10, top: 10),
                    height: 30,
                    child: Row(
                      children: [
                        const Text('Generator & Analytics',
                            style: TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 13,
                            )),
                        const Spacer(),
                        Container(
                          height: 35,
                          width: 80,
                          // alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: DL_Config.DL_MainColor,
                              borderRadius: const BorderRadius.all(
                                  Radius.circular(35 * 0.5))),
                          child: Center(
                            child: TextButton(
                                onPressed: () {
                                  debugPrint('Generate');
                                  // _generateRandomNumbers(_typeIndex);
                                  // if (widget.generateSuccess != null) {
                                  //   widget.generateSuccess!(scoredForNumbers);
                                  // }
                                  _generate();
                                },
                                child: const Text(
                                  'Generate',
                                  style: TextStyle(
                                    fontSize: 11,
                                    fontWeight: FontWeight.w400,
                                    color: Colors.white,
                                  ),
                                )),
                          ),
                        )
                      ],
                    ),
                  ),
                  // DL_drawNumbersView(data: _numbersMap),
                  drawingNumbersView(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget drawingNumbersView() {
    return Container(
      margin: const EdgeInsets.all(10),
      child: DL_drawNumbersView(data: _numbersMap),
    );
  }
}
